package com.ywy.service.impl;

import com.ywy.dao.UserDownloadDao;
import com.ywy.entity.UserDownload;
import com.ywy.service.UserDownloadService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.util.List;

/**
 * 用户下载Service实现类
 *
 * @author ywy
 * @date 2022/9/8 13:40
 */
@Transactional
@Service
public class UserDownloadServiceImpl implements UserDownloadService {
    @Resource
    private UserDownloadDao userDownloadDao;

    @Override
    public List<UserDownload> list(UserDownload userDownload, Integer pageNo, Integer pageSize) {
        Pageable pageable = new PageRequest(pageNo - 1, pageSize, Sort.Direction.DESC, "downloadDate");
        Page<UserDownload> pageMessage = userDownloadDao.findAll(createSpecification(userDownload), pageable);
        return pageMessage.getContent();
    }

    @Override
    public long getTotal(UserDownload userDownload) {
        return userDownloadDao.count(createSpecification(userDownload));
    }

    @Override
    public int getCountByUserIdAndResId(Integer userId, Integer resId) {
        return userDownloadDao.getCountByUserIdAndResId(userId, resId);
    }

    @Override
    public UserDownload save(UserDownload userDownload) {
        return userDownloadDao.save(userDownload);
    }

    private Specification<UserDownload> createSpecification(UserDownload userDownload) {
        return (root, criteriaQuery, criteriaBuilder) -> {
            Predicate predicate = criteriaBuilder.conjunction();
            if (userDownload != null) {
                if (userDownload.getUser() != null && userDownload.getUser().getId() != null) {
                    predicate.getExpressions().add(criteriaBuilder.equal(root.get("user").get("id"), userDownload.getUser().getId()));
                }
            }
            return predicate;
        };
    }
}
